<script setup lang="ts">
  import { ECharts, EChartsOption, init } from 'echarts'
  import { ref, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'

  // 定义props
  interface Props {
    option: EChartsOption | undefined
  }
  const props = withDefaults(defineProps<Props>(), {
    width: '100%',
    height: '100%',
    option: () => ({}),
  })

  const myChartsRef = ref<HTMLDivElement>()
  let myChart: ECharts
  // eslint-disable-next-line no-undef
  let timer: string | number | NodeJS.Timeout | undefined

  // 初始化echarts
  const initChart = (): void => {
    if (myChart !== undefined) {
      myChart.dispose()
    }
    myChart = init(myChartsRef.value as HTMLDivElement)
    // 拿到option配置项，渲染echarts
    myChart?.setOption(props.option, true)
  }

  // 重新渲染echarts
  const resizeChart = (): void => {
    console.log('resizeChart')
    nextTick(() => {
      if (myChart) {
        myChart.resize()
      }
    })
  }

  onMounted(() => {
    initChart()
    window.addEventListener('resize', resizeChart)
    myChart.resize()
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart)
  })

  watch(
    props.option,
    () => {
      console.log('option change')
      initChart()
      nextTick(() => {
        if (myChart) {
          myChart.resize()
        }
      })
    },
    {
      deep: true,
    },
  )
</script>

<template>
  <div ref="myChartsRef" :style="{ flex: 1 }" :option="option"></div>
</template>
